package com.eques.util;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.os.StatFs;
import android.provider.MediaStore;
import android.text.format.Time;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.eques.icvss.utils.ELog;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class FileHelper {

    private static final String TAG = "FileHelper";

    public static final String LOG_ZIP_DIR = "/eques/dingdong";// 日志压缩包缓存目录
    public static final String LOG_DIR = "/eques/dingdong/log";// 日志缓存目录

    private static final int FILE_BUFFER_SIZE = 51200;

    public static boolean hasSDCard() {
        String status = Environment.getExternalStorageState();
        return (status.equals(Environment.MEDIA_MOUNTED));
    }

    /**
     * 获取手机内存/sdcard 根目录
     *
     * @return
     */
    public static String getRootFilePath(Context context) {
        if (hasSDCard()) {
            return context.getExternalCacheDir().getPath() ;
        } else {
            return context.getCacheDir().getPath();
        }

    }
    /**
     * 获取手机内存/sdcard 根目录
     *
     * @return
     */
    public static String getRootFilePathForLogs(Context context) {
        if (hasSDCard()) {
            return context.getExternalCacheDir().getPath() ;
        } else {
            return context.getCacheDir().getPath() ;
        }
    }

    public static void insertToAlbum(Context context,String path){
        ContentValues values = new ContentValues();
        values.put(MediaStore.Video.Media.DATA, path);
        context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
    }

    public static boolean fileIsExist(String filePath) {
        if (filePath == null || filePath.length() < 1) {
            ELog.e("param invalid, filePath: " + filePath);
            return false;
        }

        File f = new File(filePath);

        return f.exists();
    }

    private static InputStream readFile(String filePath) {
        if (null == filePath) {
            ELog.e(" Invalid param. filePath is null... ");
            return null;
        }

        InputStream is;
        try {
            if (fileIsExist(filePath)) {
                File f = new File(filePath);
                is = new FileInputStream(f);
            } else {
                return null;
            }
        } catch (Exception ex) {
            ELog.e("Exception, ex: " + ex.toString());
            return null;
        }
        return is;
    }

    public static boolean createDirectory(String filePath) {
        if (null == filePath) {
            return false;
        }

        File file = new File(filePath);

        if (file.exists()) {
            ELog.i(TAG, " Capture file.exists true");
            return true;
        }
        boolean bo = file.mkdirs();
        ELog.i(TAG, " Capture file.mkdirs: ", bo);
        return bo;

    }

    /**
     * 删除文件夹和文件夹里面的文件 执行
     *
     * @param pPath 要删除的文件夹路径
     */
    public static boolean deleteDirectory(String pPath) {
        if (null == pPath) {
            ELog.e(" Invalid param. deleteDirectory() pPath is null... ");
            return false;
        }
        File dir = new File(pPath);
        if (dir.isDirectory()) {
            return deleteDirAndFile(dir, true);
        }
        return dir.delete();
    }

    /**
     * 删除文件夹和文件夹里面的文件 执行步骤
     *
     * @param dirFile 要删除的目录文件
     */
    private static boolean deleteDirAndFile(File dirFile, boolean bo) {
        if (dirFile == null || !dirFile.exists() || !dirFile.isDirectory()) {
            ELog.e(" Invalid param. deleteDirWihtFile() dirFile is null or not exists or not isDirectory... ");
            return false;
        }
        // 判断文件夹是否为空
        File[] listFiles = dirFile.listFiles();
        if (listFiles != null && listFiles.length > 0) {
            // 有文件就可以执行遍历操作
            for (File file : listFiles) {
                if (file.isFile()) {
                    file.delete(); // 删除所有文件
                } else if (file.isDirectory()) {
                    deleteDirAndFile(file, true); // 递规的方式删除文件夹
                }
            }
        } else {
            // 没有文件，可以直接删除该文件夹
        }

        if (bo) {
            dirFile.delete();// 删除目录本身
        }
        return true;
    }

    /**
     * 删除指定目录下文件
     *
     * @param filePath 目标路径
     * @param bo       是否删除目录, true 删除  false 不删除
     * @return true: 	删除成功    false： 删除失败
     */
    public static boolean deleteDirectoryFile(String filePath, boolean bo) {
        if (null == filePath) {
            ELog.e(" Invalid param. filePath is null... ");
            return false;
        }
        File file = new File(filePath);
        return deleteDirAndFile(file, bo);
    }

    public static boolean writeFile(String filePath, InputStream inputStream) {
        if (null == filePath || filePath.length() < 1) {
            return false;
        }

        if (null == inputStream) {
            return false;
        }

        try {
            File file = new File(filePath);
            if (file.exists()) {
                deleteDirectory(filePath);
            }

            String pth = filePath.substring(0, filePath.lastIndexOf("/"));
            boolean ret = createDirectory(pth);
            if (!ret) {
                ELog.e("createDirectory fail path = " + pth);
                return false;
            }

            boolean ret1 = file.createNewFile();
            if (!ret1) {
                ELog.e("createNewFile fail filePath = " + filePath);
                return false;
            }

            ELog.e(TAG, "FileHelper-->writeFile start, currentTimeMillis: ", String.valueOf(System.currentTimeMillis()));

            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int c = inputStream.read(buf);
            while (-1 != c) {
                fileOutputStream.write(buf, 0, c);
                c = inputStream.read(buf);
            }

            fileOutputStream.flush();
            fileOutputStream.close();

            ELog.e(TAG, "FileHelper-->writeFile end, currentTimeMillis: ", String.valueOf(System.currentTimeMillis()));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }

	/*public static boolean writeFile(String filePath, String fileContent) {
		return writeFile(filePath, fileContent, false);
	}

	private static boolean writeFile(String filePath, String fileContent,
									boolean append) {
		if (null == filePath || fileContent == null || filePath.length() < 1
				|| fileContent.length() < 1) {
			log.e("Invalid param. filePath: " + filePath + ", fileContent: "
					+ fileContent);
			return false;
		}

		try {
			File file = new File(filePath);
			if (!file.exists()) {
				if (!file.createNewFile()) {
					return false;
				}
			}

			BufferedWriter output = new BufferedWriter(new FileWriter(file,
					append));
			output.write(fileContent);
			output.flush();
			output.close();
		} catch (IOException ioe) {
			log.e("writeFile ioe: " + ioe.toString());
			return false;
		}

		return true;
	}*/

    public static long getFileSize(String filePath) {
        if (null == filePath) {
            ELog.e(" Invalid param. filePath is null... ");
            return 0;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            return 0;
        }

        return file.length();
    }

    public static long getFileModifyTime(String filePath) {
        if (null == filePath) {
            ELog.e(" Invalid param. filePath is null... ");
            return 0;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            return 0;
        }

        return file.lastModified();
    }

    public static boolean setFileModifyTime(String filePath, long modifyTime) {
        if (null == filePath) {
            ELog.e(" Invalid param. filePath is null... ");
            return false;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }

        return file.setLastModified(modifyTime);
    }

    public static boolean copyFile(ContentResolver cr, String fromPath,
                                   String destUri) {
        if (null == cr || null == fromPath || fromPath.length() < 1
                || null == destUri || destUri.length() < 1) {
            ELog.e("copyFile Invalid param. cr=" + cr + ", fromPath=" + fromPath
                    + ", destUri=" + destUri);
            return false;
        }

        OutputStream os = null;
        try (InputStream is = new FileInputStream(fromPath)) {
            // check output uri
            String path = null;
            Uri uri = null;

            String lwUri = destUri.toLowerCase();
            if (lwUri.startsWith("content://")) {
                uri = Uri.parse(destUri);
            } else if (lwUri.startsWith("file://")) {
                uri = Uri.parse(destUri);
                path = uri.getPath();
            } else {
                path = destUri;
            }

            // open output
            if (null != path) {
                File fl = new File(path);
                String pth = path.substring(0, path.lastIndexOf("/"));
                File pf = new File(pth);

                if (pf.exists() && !pf.isDirectory()) {
                    pf.delete();
                }

                pf = new File(pth + File.separator);

                if (!pf.exists()) {
                    if (!pf.mkdirs()) {
                        ELog.e("Can't make dirs, path=" + pth);
                    }
                }

                pf = new File(path);
                if (pf.exists()) {
                    if (pf.isDirectory())
                        deleteDirectory(path);
                    else
                        pf.delete();
                }

                os = new FileOutputStream(path);
                fl.setLastModified(System.currentTimeMillis());
            } else {
                os = new ParcelFileDescriptor.AutoCloseOutputStream(
                        cr.openFileDescriptor(uri, "w"));
            }

            // copy file
            byte[] dat = new byte[1024];
            int i = is.read(dat);
            while (-1 != i) {
                os.write(dat, 0, i);
                i = is.read(dat);
            }

            os.flush();
            os.close();
            os = null;

            return true;
        } catch (Exception ex) {
            ELog.e("Exception, ex: " + ex.toString());
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 拷贝一个文件,srcFile源文件，destFile目标文件
     */

    private static boolean copyFileTo(File srcFile, File destFile) throws IOException {

        if (srcFile.isDirectory() || destFile.isDirectory())

            return false;// 判断是否是文件

        FileInputStream fis = new FileInputStream(srcFile);

        FileOutputStream fos = new FileOutputStream(destFile);

        int readLen;

        byte[] buf = new byte[1024];

        while ((readLen = fis.read(buf)) != -1) {

            fos.write(buf, 0, readLen);

        }

        fos.flush();

        fos.close();

        fis.close();

        return true;

    }

    /**
     * 拷贝目录下的所有文件到指定目录
     *
     * @param srcDir  源目录
     * @param destDir 目标目录
     */
    private static boolean copyFilesTo(File srcDir, File destDir) throws IOException {

        if (!srcDir.isDirectory() || !destDir.isDirectory())

            return false;// 判断是否是目录

        if (!destDir.exists())

            return false;// 判断目标目录是否存在

        File[] srcFiles = srcDir.listFiles();
        for (File srcFile : srcFiles) {
            if (srcFile.isFile()) {
                // 获得目标文件
                File destFile = new File(destDir.getPath() + "//"
                        + srcFile.getName());
                copyFileTo(srcFile, destFile);
            } else if (srcFile.isDirectory()) {
                File theDestDir = new File(destDir.getPath() + "//"
                        + srcFile.getName());
                copyFilesTo(srcFile, theDestDir);

            }
        }
        return true;
    }

    /**
     * 拷贝单个文件
     *
     * @param srcFilePath  源文件路径
     * @param destFilePath 目的文件路径
     */
    public static boolean copyFileTo(String srcFilePath, String destFilePath)

            throws IOException {

        File srcFile = new File(srcFilePath);

        File destFile = new File(destFilePath);
        ELog.e("test_upload_log:", " copyFileTo 文件 ");

        return copyFileTo(srcFile, destFile);

    }


    /**
     * 拷贝指定目录下的所有文件
     */

    public static boolean copyFilesTo(String srcDirPath, String destDirPath)

            throws IOException {

        File srcDir = new File(srcDirPath);

        File destDir = new File(destDirPath);

        return copyFilesTo(srcDir, destDir);

    }

    private static byte[] readAll(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        byte[] buf = new byte[1024];
        int c = is.read(buf);
        while (-1 != c) {
            baos.write(buf, 0, c);
            c = is.read(buf);
        }
        baos.flush();
        baos.close();
        return baos.toByteArray();
    }

    public static byte[] readFile(Context ctx, Uri uri) {
        if (null == ctx || null == uri) {
            ELog.e("Invalid param. ctx: " + ctx + ", uri: " + uri);
            return null;
        }

        InputStream is = null;
        String scheme = Objects.requireNonNull(uri.getScheme()).toLowerCase();
        if (scheme.equals("file")) {
            is = readFile(uri.getPath());
        }

        try {
            is = ctx.getContentResolver().openInputStream(uri);
            if (null == is) {
                return null;
            }

            byte[] bret = readAll(is);
            is.close();
            is = null;

            return bret;
        } catch (FileNotFoundException fne) {
            ELog.e("FilNotFoundException, ex: " + fne.toString());
        } catch (Exception ex) {
            ELog.e("Exception, ex: " + ex.toString());
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static boolean writeFile(String filePath, byte[] content) {
        if (null == filePath || null == content) {
            ELog.e("Invalid param. filePath: " + filePath + ", content: "
                    + Arrays.toString(content));
            return false;
        }

        FileOutputStream fos = null;
        try {
            String pth = filePath.substring(0, filePath.lastIndexOf("/"));
            File pf;
            pf = new File(pth);
            if (pf.exists() && !pf.isDirectory()) {
                pf.delete();
            }
            pf = new File(filePath);
            if (pf.exists()) {
                if (pf.isDirectory())
                    FileHelper.deleteDirectory(filePath);
                else
                    pf.delete();
            }

            pf = new File(pth + File.separator);
            if (!pf.exists()) {
                if (!pf.mkdirs()) {
                    ELog.e("Can't make dirs, path=" + pth);
                }
            }

            fos = new FileOutputStream(filePath);
            fos.write(content);
            fos.flush();
            fos.close();
            fos = null;
            pf.setLastModified(System.currentTimeMillis());

            return true;

        } catch (Exception ex) {
            ELog.e("Exception, ex: " + ex.toString());
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public static boolean writeFile(String filePath, File imagefile) {
        if (null == filePath || filePath.length() < 1) {
            return false;
        }

        try {
            File file = new File(filePath);
            if (file.exists()) {
                deleteDirectory(filePath);
            }

            String pth = filePath.substring(0, filePath.lastIndexOf("/"));
            boolean ret = createDirectory(pth);
            if (!ret) {
                ELog.e("createDirectory fail path = " + pth);
                return false;
            }

            boolean ret1 = file.createNewFile();
            if (!ret1) {
                ELog.e("createNewFile fail filePath = " + filePath);
                return false;
            }

            FileInputStream inputStream = new FileInputStream(file);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int c = inputStream.read(buf);
            while (-1 != c) {
                fileOutputStream.write(buf, 0, c);
                c = inputStream.read(buf);
            }

            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }

    /*************
     * ZIP file operation
     ***************/
    public static boolean readZipFile(String zipFileName, StringBuffer crc) {
        try {
            ZipInputStream zis = new ZipInputStream(new FileInputStream(
                    zipFileName));
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                long size = entry.getSize();
                crc.append(entry.getCrc()).append(", size: ").append(size);
            }
            zis.close();
        } catch (Exception ex) {
            ELog.e("Exception: " + ex.toString());
            return false;
        }
        return true;
    }

    public static byte[] readGZipFile(String zipFileName) {
        if (fileIsExist(zipFileName)) {
            ELog.i("zipFileName: " + zipFileName);
            try {
                FileInputStream fin = new FileInputStream(zipFileName);
                int size;
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((size = fin.read(buffer, 0, buffer.length)) != -1) {
                    baos.write(buffer, 0, size);
                }
                return baos.toByteArray();
            } catch (Exception ex) {
                ELog.i("read zipRecorder file error");
            }
        }
        return null;
    }

    public static boolean zipFile(String baseDirName, String fileName,
                                  String targerFileName) throws IOException {
        if (baseDirName == null || "".equals(baseDirName)) {
            return false;
        }
        File baseDir = new File(baseDirName);
        if (!baseDir.exists() || !baseDir.isDirectory()) {
            return false;
        }

        String baseDirPath = baseDir.getAbsolutePath();
        File targerFile = new File(targerFileName);
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                targerFile));
        File file = new File(baseDir, fileName);

        boolean zipResult;
        if (file.isFile()) {
            zipResult = fileToZip(baseDirPath, file, out);
        } else {
            zipResult = dirToZip(baseDirPath, file, out);
        }
        out.close();
        return zipResult;
    }

	/*private static boolean fileToZip(String baseDirPath, File file,
									 ZipOutputStream out) throws IOException {
		FileInputStream in = null;
		ZipEntry entry = null;

		byte[] buffer = new byte[FILE_BUFFER_SIZE];
		int bytes_read;
		try {
			in = new FileInputStream(file);
			entry = new ZipEntry(getEntryName(baseDirPath, file));
			out.putNextEntry(entry);

			while ((bytes_read = in.read(buffer)) != -1) {
				out.write(buffer, 0, bytes_read);
			}
			out.closeEntry();
			in.close();
		} catch (IOException e) {
			log.e("Exception, ex: " + e.toString());
			return false;
		} finally {
			if (out != null) {
				out.closeEntry();
			}

			if (in != null) {
				in.close();
			}
		}
		return true;
	}*/

    private static boolean fileToZip(String baseDirPath, File file,
                                     ZipOutputStream out) throws IOException {

        ZipEntry entry;
        byte[] buffer = new byte[FILE_BUFFER_SIZE];
        int bytes_read;
        /*
         * 当代码块中代码终止，不管是正常还是异常，FileInputStream对象的close方法都会自动按声明的相反顺序调用
         * 在try-with-resources语句中，任何的catch和finally代码块都在所有被声明的资源被关闭后执行
         */
        try (FileInputStream in = new FileInputStream(file)) {
            entry = new ZipEntry(getEntryName(baseDirPath, file));
            out.putNextEntry(entry);

            while ((bytes_read = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytes_read);
            }
            out.closeEntry();
        } catch (IOException e) {
            ELog.e("Exception, ex: " + e.toString());
            return false;
        } finally {
            if (out != null) {
                out.closeEntry();
            }

        }
        return true;
    }

    private static boolean dirToZip(String baseDirPath, File dir,
                                    ZipOutputStream out) throws IOException {
        if (!dir.isDirectory()) {
            return false;
        }

        File[] files = dir.listFiles();
        if (files.length == 0) {
            ZipEntry entry = new ZipEntry(getEntryName(baseDirPath, dir));

            try {
                out.putNextEntry(entry);
                out.closeEntry();
            } catch (IOException e) {
                ELog.e("Exception, ex: " + e.toString());
            }
        }
        for (File file : files) {
            if (file.isFile()) {
                fileToZip(baseDirPath, file, out);
            } else {
                dirToZip(baseDirPath, file, out);
            }
        }
        return true;
    }

    private static String getEntryName(String baseDirPath, File file) {
        if (!baseDirPath.endsWith(File.separator)) {
            baseDirPath = baseDirPath + File.separator;
        }

        String filePath = file.getAbsolutePath();
        if (file.isDirectory()) {
            filePath = filePath + "/";
        }

        int index = filePath.indexOf(baseDirPath);
        return filePath.substring(index + baseDirPath.length());
    }

    /**
     * Resize the bitmap
     */
    public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }

    private static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath);
            File myFilePath = new File(folderPath);
            myFilePath.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除该文件夹及其以下的所有文件
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp;
        for (String tempListItem : tempList) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempListItem);
            } else {
                temp = new File(path + File.separator + tempListItem);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + File.separator + tempListItem);// 删除所有文件
                delFolder(path + File.separator + tempListItem);// 删除文件夹
            }
        }
    }

    public static String[] getPathFolderName(String folderPath) {
        ArrayList<String> camFolderNames = new ArrayList<>();
        File f = new File(folderPath);
        String[] files = f.list();
        if (files != null) {
            for (String file : files) {
                String path = folderPath + File.separator + file;
                File f2 = new File(path);
                if (f2.isDirectory()) {
                    int len = f2.list().length;
                    if (len > 0) {
                        camFolderNames.add(f2.getName());
                    } else {
                        deleteDirectory(path);
                    }
                }
            }
        }

        String[] files02 = new String[camFolderNames.size()];
        for (int i = 0; i < camFolderNames.size(); i++) {
            files02[i] = camFolderNames.get(i);
        }
        return files02;
    }

    /**
     * 获取文件夹下文件名
     *
     * @param folderPath 文件夹路径
     */
    public static String[] getPathImageNames(String folderPath) {
        File file01 = new File(folderPath);
        String[] files01 = file01.list();

        if (files01 == null) {
            ELog.e(TAG, "ERROR, getPathImageNames file.list() is Null...");
            return null;
        }

        if (files01.length <= 0) {
            ELog.e(TAG, "ERROR, getPathImageNames files01.length <= 0...");
            return null;
        }

        ArrayList<String> arrayList = new ArrayList<>();
        for (String fileStr : files01) {
            File file02 = new File(folderPath + File.separator + fileStr);
            if (!file02.isDirectory() && isImageFile(file02.getName())) {
                arrayList.add(file02.getName());
            }
        }

        String[] files02 = new String[arrayList.size()];
        int len = arrayList.size();
        for (int i = 0; i < len; i++) {
            files02[i] = arrayList.get(i);
        }
        return files02;
    }

    private static boolean isImageFile(String fileName) {
        String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1);
        return (fileEnd.equalsIgnoreCase("jpg")
                || fileEnd.equalsIgnoreCase("png")
                || fileEnd.equalsIgnoreCase("bmp"));
    }

    /**
     * 得带sd的存储空间信息
     */
    private static long getSdInfo(Context ctx) {
        //此处为data/data路径下的存储空间
        //得到路径下的存储空间的状态，根据此状态得到各种属性
        StatFs statfs = new StatFs(getRootFilePath(ctx));
        /*
         * API 18之后添加以下方法，现在最低支持API 19，所以不需要往下兼容
         */
        long blocSize = statfs.getBlockSizeLong();
        long availaBlock = statfs.getAvailableBlocksLong();
        //格式化，将数字转化为存储空间的字节大小
        // String free = Formatter.formatFileSize(ctx, blockSize*freeBlocks);  //返回当前路径下的可用空间
        return blocSize * availaBlock;//返回当前路劲可用空间
    }

    public static boolean getMemorySize(Context ctx) {
        long size = getSdInfo(ctx);
        System.out.println(size);
        boolean bool = false;
        size /= 1024 * 1024;
        if (size > 50) {
            ELog.v(TAG, " getMemorySize size: ", size);
            bool = true;
        }
        return bool;
    }
	/*private static void fileRenameTo(Context ctx, String camSn){
		String path = Sysconfig.getCameraBgPath(ctx, camSn);
		String path_new = path +"eqcam" +File.separator +"55667788/"+"gbuejt0640"+File.separator +"cameraPicture";//新的下载图片路径
		path = path +"eqcam" +File.separator +"55667788/"+"gbuejt0640"+File.separator +"cameraPicture"+ File.separator +"gbuejt0640.jpg";//之前路径
		
		FileHelper.delFolder(path);
		
		File from =new File(path_new, "gbuejt0640_new.jpg") ;
		File to=new File(path_new, "gbuejt0640.jpg") ;
		from.renameTo(to) ;
	}*/

    public static ArrayList<String> readFileByLines(String path) {
        File f = new File(path);

        BufferedReader br = null;
        String tmp;
        ArrayList<String> list = new ArrayList<>();

        try {
            br = new BufferedReader(new FileReader(f));
            while ((tmp = br.readLine()) != null) {
                list.add(tmp);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * 判断当前系统时间是否在指定时间的范围内
     *
     * @param beginHour 开始小时，例如22
     * @param beginMin  开始小时的分钟数，例如30
     * @param endHour   结束小时，例如 8
     * @param endMin    结束小时的分钟数，例如0
     * @return true表示在范围内，否则false
     */
    public static boolean isCurrentInTimeScope(int beginHour, int beginMin, int endHour, int endMin) {
        boolean result;
        final long aDayInMillis = 1000 * 60 * 60 * 24;
        final long currentTimeMillis = System.currentTimeMillis();

        Time now = new Time();
        now.set(currentTimeMillis);

        Time startTime = new Time();
        startTime.set(currentTimeMillis);
        startTime.hour = beginHour;
        startTime.minute = beginMin;

        Time endTime = new Time();
        endTime.set(currentTimeMillis);
        endTime.hour = endHour;
        endTime.minute = endMin;

        if (!startTime.before(endTime)) {
            // 跨天的特殊情况（比如22:00-8:00）
            startTime.set(startTime.toMillis(true) - aDayInMillis);
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
            Time startTimeInThisDay = new Time();
            startTimeInThisDay.set(startTime.toMillis(true) + aDayInMillis);

            if (!now.before(startTimeInThisDay)) {
                result = true;
            }
        } else {
            // 普通情况(比如 8:00 - 14:00)
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
        }
        return result;
    }

    /**
     * 图片是否损坏
     */
    public static boolean isComplete(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options); //filePath代表图片路径
        return (options.mCancel || options.outWidth == -1 || options.outHeight == -1); //表示图片已损
    }

    public static void copyVideoToAlbum(Context context, String videoPath) {
        // 检查存储权限
        File sourceFile = new File(videoPath);
        if (!sourceFile.exists()) {
            ELog.e(TAG, "源视频文件不存在");
            return;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                // 请求存储权限
                ActivityCompat.requestPermissions((android.app.Activity) context,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        101);
                return;
            }
        }
        // 获取相册目录的 Uri
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();

        try {
            File dest = new File(path, sourceFile.getName());
            // 拷贝文件到相册目录
            copyFileTo(sourceFile, dest);

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(dest);
            intent.setData(uri);
            context.sendBroadcast(intent);
            ELog.e(TAG, "save success " + path);

        } catch (Exception e) {
            e.printStackTrace();
            ELog.e(TAG, "save error" + e.getMessage());
            addVideoToAlbum(context,sourceFile);
        }
    }


    /**
     * 保存视频到相册
     */
    public static void addVideoToAlbum(Context context,File file) {
        ContentResolver localContentResolver = context.getContentResolver();
        ContentValues localContentValues = getVideoContentValues(file, System.currentTimeMillis());
        Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);

        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(localUri);
        context.sendBroadcast(intent);
    }


    public static ContentValues getVideoContentValues(File paramFile, long paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "video/mp4");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;

    }
    /**
     * 获取指定文件大小
     */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fileInputStream = new FileInputStream(file);
            size = fileInputStream.available();

            fileInputStream.close();
        }
        return size;
    }

    /**
     * 是否有日志文件
     *
     * @return
     */
    public static boolean isHasLogsFile(Context context) {
        boolean isHasLogsFile = false;
        String logDirectory = getRootFilePathForLogs(context) + LOG_DIR;
        if (StringUtils.isNotBlank(logDirectory)) {
            File file = new File(logDirectory);
            if (file.exists() && file.isDirectory() && file.list().length > 0) {
                isHasLogsFile = true;
            }
        }
        return isHasLogsFile;
    }

}